use sdl2::rect::Rect as SdlRect;

#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Rectangle {
    pub x: f64,
    pub y: f64,
    pub w: f64,
    pub h: f64,
}

impl Rectangle {
    pub fn new(x: f64, y: f64, w: f64, h: f64) -> Self {
        Self { x, y, w, h }
    }
    pub fn to_sdl(&self) -> Option<SdlRect> {
        assert!(self.w >= 0.0 && self.h >= 0.0);
        Some(SdlRect::new(
            self.x as i32,
            self.y as i32,
            self.w as u32,
            self.h as u32,
        ))
    }
    pub fn move_inside(self, parent: Rectangle) -> Option<Rectangle> {
        if self.w > parent.w || self.h > parent.h {
            return None;
        }
        Some(Rectangle {
            w: self.w,
            h: self.h,
            x: if self.x < parent.x {
                parent.x
            } else if self.x + self.w >= parent.x + parent.w {
                parent.x + parent.w - self.w
            } else {
                self.x
            },
            y: if self.y < parent.y {
                parent.y
            } else if self.y + self.h >= parent.y + parent.h {
                parent.y + parent.h - self.h
            } else {
                self.y
            },
        })
    }

    pub fn contains(&self, rect: Rectangle) -> bool {
        let x_min = rect.x;
        let x_max = x_min + rect.w;
        let y_min = rect.y;
        let y_max = y_min + rect.h;

        x_min >= self.x
            && x_min <= self.x + self.w
            && x_max >= self.x
            && x_max <= self.x + self.w
            && y_min >= self.y
            && y_min <= self.y + self.h
            && y_max >= self.y
            && y_max <= self.y + self.h
    }
}
